#!/bin/bash

projectName="yudao-server"

JAVA_OPTIONS="-Xms2g -Xmx2g -Dfile.encoding=UTF-8 -Dclient.encoding.override=UTF-8 -Dspring.config.location=./../config/application.yaml -Dlogging.config=./../config/logback-spring.xml"

echo "==========启动${projectName}========="
pidList=$(ps -ef | grep java | grep "$projectName" | grep -v grep | awk '{print $2}')
if [ "$pidList" ]; then
    echo "${projectName}服务已启动, 是否需要先停止服务? (y/n)"
    read stopFlag
    if [ "$stopFlag" == "y" ]; then
        kill -9 $pidList
    fi
    echo "${projectName}服务正在停止..."
    i=5
    while [ $i -gt 0 ]
    do
        echo -n "."
        sleep 1
        pidList=$(ps -ef | grep java | grep "$projectName" | grep -v grep | awk '{print $2}')
        if [ -z "$pidList" ]; then
            break
        fi
        i=$(($i-1))
    done
    if [ "$pidList" ]; then
        echo "${projectName}服务停止失败, 请手动停止"
        exit 1
    fi
    echo "${projectName}服务已停止"
    sleep 2
fi

cd ../dist_lib
sys=`uname`
echo "${projectName}服务开始启动..."
if [[ $sys == 'Darwin' ]]; then
    java -jar ${JAVA_OPTIONS}  ${projectName}.jar > /dev/null &
else
    setsid java -jar ${JAVA_OPTIONS}  ${projectName}.jar > /dev/null &
fi

sleep 5

pidList=$(ps -ef | grep java | grep "$projectName" | grep -v grep | awk '{print $2}')
if [ "$pidList" ]; then
    echo "${projectName}服务启动成功"
else
    echo "${projectName}服务启动失败, 请检查日志"
fi